package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //校验参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //根据id查询评论回复的列表
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate())).limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //如果未登录或没有回复直接返回
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || apCommentRepays == null || apCommentRepays.size() == 0) {
            return ResponseResult.okResult(apCommentRepays);
        }

        //判断参数,不存在则直接返回
        List<String> commentRepayIds = apCommentRepays.stream()
                .map(ApCommentRepay::getId)
                .collect(Collectors.toList());
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query
                        .query(Criteria.where("authorId").is(user.getId())
                                .and("commentRepayId").in(commentRepayIds)),
                ApCommentRepayLike.class);
        if (apCommentRepayLikes == null || apCommentRepayLikes.size() == 0) {
            return ResponseResult.okResult(apCommentRepays);
        }

        List<String> likedCommentRepayIds = apCommentRepayLikes.stream()
                .map(ApCommentRepayLike::getCommentRepayId)
                .collect(Collectors.toList());
        // 说明有点过赞的回复
        List<ApCommentRepayVo> apCommentRepayVoList = new ArrayList<>();
        apCommentRepays.forEach(apCommentRepay -> {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVo);
            if (likedCommentRepayIds.contains(apCommentRepay.getId())) {
                apCommentRepayVo.setOperation((short) 0);
            }
            apCommentRepayVoList.add(apCommentRepayVo);
        });
        return ResponseResult.okResult(apCommentRepayVoList);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //校验参数,登录
        if (dto == null || StringUtils.isBlank(dto.getContent()) ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<ApUser> userResult = userFeign.findUserById(user.getId());
        if(userResult.getCode()!=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, userResult.getErrorMessage());
        }
        user = userResult.getData();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }

        //评论安全审核,暂不添加,采用阿里云
        //todo

        //保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);

        //更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //校验参数,登录
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询点赞操作和个人点赞操作
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Query query = Query.query(Criteria.where("authorId").is(user.getId())
                .and("commentRepayId").is(commentRepay.getId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);

        //判断并执行操作
        if (dto.getOperation() == 0){
            //点赞
            if(apCommentRepayLike != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
            }
            //更新评论的点赞数量
            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);
            //保存 APP评论信息点赞
            ApCommentRepayLike apCommentLike = new ApCommentRepayLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentRepayId(commentRepay.getId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);
        }else if (dto.getOperation() == 1){
            if(apCommentRepayLike == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"您还没有点赞");
            }
            //更新评论的点赞数量
            commentRepay.setLikes(commentRepay.getLikes() < 0 ? 0 : commentRepay.getLikes() - 1);
            mongoTemplate.save(commentRepay);
            //更新 APP评论信息点赞
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",commentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
